package io.github.veigara.tcp.device.protocol.charger;

import io.github.veigara.tcp.framework.protocol.ProtocolEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteOrder;
import java.util.List;

/**
 * @author : zhouhx
 * 充电机协议编码器,用于发送消息
 * @date : 2025/6/6 13:53
 */
public class ChargingPileEncoder extends MessageToMessageEncoder<ChargingPileSendMessage> implements ProtocolEncoder<ChargingPileSendMessage> {
    private static final Logger logger = LoggerFactory.getLogger(ChargingPileEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, ChargingPileSendMessage chargingPileMessage, List<Object> out) throws Exception {
        out.add(encode(chargingPileMessage));
    }

    @Override
    public ByteBuf encode(ChargingPileSendMessage message) {
        ByteBuf buf = io.netty.buffer.Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);;

        try {
            buf.writeShort((short) 0xF5AA);
            buf.writeShort((short) message.getLength());
            buf.writeByte(message.getInfoField());
            buf.writeByte(message.getSequence());
            buf.writeShort((short) message.getCmd());



            return buf;

        } catch (Exception e) {
            buf.release();
            throw new RuntimeException("Failed to encode message", e);
        }

    }
}
